﻿using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Chemistry.Tools
{
    /// <summary>
    /// 考生、成绩 Http（用于登录、获取考生、上传成绩）
    /// </summary>
    public sealed class HttpBasePrimary
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static readonly HttpClient Client ;
        public static string Session = string.Empty;
        private HttpBasePrimary() { }

        static HttpBasePrimary()
        {
            Client = new HttpClient();
            Client.BaseAddress = new Uri(ConfigurationManager.AppSettings["SERVERADDRESS"]);
            Client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }

        private static HttpClient GetHttpBase()
        {
            if (Client == null || Client.BaseAddress == null)
            {
                Client.BaseAddress = new Uri(ConfigurationManager.AppSettings["SERVERADDRESS"]);
                //Client.DefaultRequestHeaders.Add("accessToken", token);
                Client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            }
            return Client;
        }

        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(string url) where T : class
        {
            HttpResponseMessage response = await Client.GetAsync(url);  
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                log.Error(string.Format("异步Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 同步Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T Get<T>(string url) where T : class
        {
            HttpResponseMessage response = GetHttpBase().GetAsync(url).Result;  // Blocking call（阻塞调用）! 
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                log.Error(string.Format("Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<Boolean> PostAsJsonAsync(string url, object entity)
        {
            HttpResponseMessage response = await GetHttpBase().PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                log.Error(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Boolean PostAsJson(string url, object entity)
        {
            HttpResponseMessage response = GetHttpBase().PostAsJsonAsync(url, entity).Result;
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                log.Error(string.Format("Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<T> PostAsJsonAsync<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = await Client.PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                log.Error(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static T PostAsJson<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = GetHttpBase().PostAsJsonAsync(url, entity).Result;
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                log.Error(string.Format("Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 异步删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<Boolean> DeleteAsync(string url)
        {
            HttpResponseMessage response = await GetHttpBase().DeleteAsync(url);
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                log.Error(string.Format("异步Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// 删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Boolean Delete(string url)
        {
            HttpResponseMessage response = GetHttpBase().DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                log.Error(string.Format("Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// 异步删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<T> DeleteAsync<T>(string url) where T : class
        {
            HttpResponseMessage response = await GetHttpBase().DeleteAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                log.Error(string.Format("异步Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T Delete<T>(string url) where T : class
        {
            HttpResponseMessage response = GetHttpBase().DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                log.Error(string.Format("Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }
    }
}
